<?php
namespace app\push\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Workerman\Worker;

class Workerman extends Command
{
    protected function configure()
    {
        $this->setName('answer:server')
            ->addArgument('action', Argument::OPTIONAL, 'start|stop|restart|reload|status', 'start')
            ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.')
            ->setDescription('抢答器WebSocket服务器');
    }

    protected function execute(Input $input, Output $output)
    {
        // 获取参数
        $action = $input->getArgument('action');
        $daemon = $input->getOption('daemon');

        // 输出信息
        $output->writeln("Answer Server Action: {$action}" . ($daemon ? ' (daemon mode)' : ''));


        // 设置工作目录为项目根目录
        chdir(realpath(ROOT_PATH));
        // 设置业务 worker 的日志文件
        Worker::$logFile = LOG_PATH . 'gateway_worker.log';
        Worker::$pidFile = RUNTIME_PATH . 'gateway_worker.pid';

        // 确保日志目录存在
        if (!is_dir(dirname(Worker::$logFile))) {
            mkdir(dirname(Worker::$logFile), 0755, true);
        }

        // 设置全局argv，供GatewayWorker使用
        global $argv;
        if ($daemon) {
            $argv = ['think', $action, '-d'];
        } else {
            $argv = ['think', $action];
        }

        // 根据action执行
        switch ($action) {
            case 'start':
                $this->start($output, $daemon);
                break;
            case 'stop':
                $this->stop($output);
                break;
            case 'restart':
                $this->stop($output);
                sleep(2);
                $this->start($output, $daemon);
                break;
            case 'reload':
                // 发送USR2信号给主进程，实现平滑重启
                if (file_exists(Worker::$pidFile)) {
                    $pid = file_get_contents(Worker::$pidFile);
                    posix_kill($pid, SIGUSR2);
                    $output->writeln("Reload signal sent to process $pid");
                } else {
                    $output->writeln("PID file not found, cannot reload");
                }
                break;
            case 'status':
                $this->status($output);
                break;
            default:
                $output->writeln("Unknown action: {$action}");
                $output->writeln("Usage: php think answer:server <start|stop|restart|reload|status> [-d]");
                break;
        }
    }

    private function start($output, $daemon)
    {
        $output->writeln('Starting Answer Server...');

        $this->startBusinessWorker();
        $this->startGateway();
        $this->startRegister();

        Worker::runAll();
    }

    private function stop($output)
    {
        $output->writeln('Stopping Answer Server...');

        // 直接调用Worker的stopAll方法
        Worker::stopAll();

        // 检查是否停止成功
        sleep(2);
        if (file_exists(Worker::$pidFile)) {
            $output->writeln('Warning: PID file still exists, processes may not have stopped properly');
            $output->writeln('You may need to manually kill the processes:');
            $output->writeln('  pkill -f Answer');
        } else {
            $output->writeln('Answer Server stopped successfully');
        }
    }

    private function status($output)
    {
        if (file_exists(Worker::$pidFile)) {
            $pid = file_get_contents(Worker::$pidFile);
            $output->writeln("Answer Server is running (PID: $pid)");

            // 检查进程是否真的在运行
            if (posix_kill($pid, 0)) {
                $output->writeln("Process $pid is alive");
            } else {
                $output->writeln("Process $pid is not running (stale PID file)");
            }
        } else {
            $output->writeln("Answer Server is not running");
        }

        // 显示相关进程
        $output->writeln("\nRelated processes:");
        exec("ps aux | grep -E '(AnswerBusinessWorker|AnswerGateway|AnswerRegister)' | grep -v grep", $processes);
        if (empty($processes)) {
            $output->writeln("No related processes found");
        } else {
            foreach ($processes as $process) {
                $output->writeln($process);
            }
        }
    }

    private function startBusinessWorker()
    {
        $worker = new BusinessWorker();
        $worker->name = 'AnswerBusinessWorker';
        $worker->count = 2; // 减少进程数，便于调试
        $worker->registerAddress = '127.0.0.1:1238';
        $worker->eventHandler = '\app\push\controller\Events';
    }

    private function startGateway()
    {
        $gateway = new Gateway("websocket://0.0.0.0:8282");
        $gateway->name = 'AnswerGateway';
        $gateway->count = 2; // 减少进程数，便于调试
        $gateway->lanIp = '127.0.0.1';
        $gateway->startPort = 2300;
        $gateway->registerAddress = '127.0.0.1:1238';

        // 心跳设置
        $gateway->pingInterval = 55;
        $gateway->pingNotResponseLimit = 1;
        $gateway->pingData = '';
    }

    private function startRegister()
    {
        $register = new Register('text://0.0.0.0:1238');
        $register->name = 'AnswerRegister';
    }
}